<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>海洋牧场监测系统</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    <style>
        body {
            margin: 0;
            font-family: "Microsoft YaHei", sans-serif;
            background-color: #f0f8ff; /* 淡蓝色背景 */
        }

        /* 顶部导航栏 */
        .navbar {
            background-color: #003366;
            padding: 15px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .navbar h1 {
            color: white;
            font-size: 24px;
            margin: 0;
            font-weight: 600;
        }

        .navbar ul {
            display: flex;
            list-style: none;
            margin: 0;
            padding: 0;
            align-items: center;
        }

        .navbar ul li {
            margin: 0 15px;
        }

        .navbar ul li a {
            color: white;
            text-decoration: none;
            font-size: 16px;
            font-weight: 500;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
        }

        .navbar ul li a:hover {
            color: #66ccff;
        }

        .navbar .nav-icon {
            margin-right: 8px;
            font-size: 18px;
        }

        .user-info {
            display: flex;
            align-items: center;
        }

        .user-info .username {
            color: white;
            margin-right: 20px;
            font-weight: 500;
            display: flex;
            align-items: center;
        }

        .user-info .username i {
            margin-right: 8px;
            color: #66ccff;
        }

        .user-info .exit a {
            padding: 8px 15px;
            background-color: #0066cc;
            border-radius: 20px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .user-info .exit a:hover {
            background-color: #004c99;
            color: white;
        }

        /* 主内容区域 */
        .main-content {
            max-width: 1200px;
            margin: 20px auto;
            padding: 0 20px;
        }

        .content-header {
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #ddd;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .content-header h2 {
            font-size: 24px;
            color: #003366;
            margin: 0;
            font-weight: 600;
        }

        /* 绘制图表按钮 */
        .chart-btn {
            background-color: #0066cc;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .chart-btn:hover {
            background-color: #004c99;
            transform: translateY(-2px);
        }

        /* 表格样式 */
        table {
            width: 100%;
            border-collapse: collapse;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
            background-color: white;
            border-radius: 8px;
            overflow: hidden;
        }

        th, td {
            padding: 15px 12px;
            text-align: center;
            font-size: 14px;
            color: #333;
        }

        th {
            background-color: #003366;
            color: white;
            font-weight: 500;
        }

        tr:nth-child(odd) {
            background-color: #f9f9f9;
        }

        tr:hover {
            background-color: #f0f8ff;
        }

        /* 状态指示器 */
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-normal {
            background-color: #4caf50;
        }

        .status-warning {
            background-color: #ff9800;
        }

        .status-danger {
            background-color: #f44336;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 0;
            border-radius: 10px;
            width: 90%;
            max-width: 900px;
            max-height: 85vh;
            overflow-y: auto;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        }

        .modal-header {
            background-color: #003366;
            color: white;
            padding: 20px;
            border-radius: 10px 10px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            margin: 0;
            font-size: 20px;
        }

        .close {
            color: white;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            line-height: 1;
        }

        .close:hover {
            color: #66ccff;
        }

        .modal-body {
            padding: 20px;
        }

        /* 参数选择区域 */
        .parameter-selection {
            margin-bottom: 20px;
        }

        .parameter-selection h4 {
            color: #003366;
            margin-bottom: 15px;
            font-size: 16px;
        }

        .parameter-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
            margin-bottom: 20px;
        }

        .parameter-item {
            display: flex;
            align-items: center;
            padding: 10px;
            background-color: #f9f9f9;
            border-radius: 5px;
            border: 2px solid transparent;
            transition: all 0.3s ease;
        }

        .parameter-item:hover {
            background-color: #f0f8ff;
            border-color: #66ccff;
        }

        .parameter-item input[type="checkbox"] {
            margin-right: 10px;
            transform: scale(1.2);
        }

        .parameter-item label {
            cursor: pointer;
            font-weight: 500;
            color: #333;
        }

        /* 控制按钮 */
        .control-buttons {
            display: flex;
            gap: 10px;
            margin-top: 20px;
            flex-wrap: wrap;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .btn-primary {
            background-color: #0066cc;
            color: white;
        }

        .btn-primary:hover {
            background-color: #004c99;
        }

        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background-color: #545b62;
        }

        .btn-success {
            background-color: #28a745;
            color: white;
        }

        .btn-success:hover {
            background-color: #218838;
        }

        .btn:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
            opacity: 0.6;
        }

        .btn:disabled:hover {
            background-color: #cccccc;
            transform: none;
        }

        /* 图表容器 */
        .chart-container {
            margin-top: 20px;
            height: 400px;
            display: none;
        }

        .chart-container canvas {
            max-height: 100%;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .navbar {
                flex-direction: column;
                padding: 15px;
            }

            .navbar ul {
                margin-top: 15px;
                flex-wrap: wrap;
                justify-content: center;
            }

            .navbar ul li {
                margin: 5px 10px;
            }

            th, td {
                padding: 10px 8px;
                font-size: 12px;
            }

            .content-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }

            .modal-content {
                width: 95%;
                margin: 2% auto;
            }

            .parameter-grid {
                grid-template-columns: 1fr;
            }

            .control-buttons {
                flex-direction: column;
            }

            .btn {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <div class="navbar">
        <div><h1>海洋牧场监测系统</h1></div>
        <ul>
            {% if userrole=="admin" %}
            <li><a href="{{ url_for('tomain') }}"><i class="home-icon"></i> 首页</a></li>
            <li><a href="{{ url_for('todata') }}"><i class="data-icon"></i> 主要信息</a></li>
            <li><a href="{{ url_for('towater') }}"><i class="underwater-icon"></i> 水下系统</a></li>
            <li><a href="{{ url_for('toai') }}"><i class="ai-icon"></i> 智能中心</a></li>
            <li><a href="{{ url_for('toadadmin') }}"><i class="admin-icon"></i> 管理员</a></li>
            {% else %}
            <li><a href="{{ url_for('tomain') }}"><i class="home-icon"></i> 首页</a></li>
            <li><a href="{{ url_for('todata') }}"><i class="data-icon"></i> 主要信息</a></li>
            <li><a href="{{ url_for('towater') }}"><i class="underwater-icon"></i> 水下系统</a></li>
            <li><a href="{{ url_for('toai') }}"><i class="ai-icon"></i> 智能中心</a></li>
            {% endif %}
        </ul>
        <div>
            <ul>
                <li><a href="{{ url_for('topersonal') }}" class="username"><i class="user-icon"></i> {{ username }}</a></li>
                <li><a href="{{ url_for('exit') }}" class="exit"><i class="exit-icon"></i> 退出</a></li>
            </ul>
        </div>
    </div>

    <div class="main-content">
        <div class="content-header">
            <h2>传感器最近动态</h2>
            <button class="chart-btn" onclick="openChartModal()">📊 绘制图表</button>
        </div>

        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>监测省份</th>
                    <th>监测地点</th>
                    <th>监测时间</th>
                    <th>水温</th>
                    <th>pH</th>
                    <th>溶解氧量</th>
                    <th>电导率</th>
                    <th>浊度</th>
                    <th>高锰酸盐指数</th>
                    <th>氨氮</th>
                    <th>总磷</th>
                    <th>总氮</th>
                    <th>状态</th>
                </tr>
            </thead>
            <tbody id="dataTable">
                {% for data in datas %}
                <tr>
                    <td>{{ data[0] }}</td>
                    <td>{{ data[1] }}</td>
                    <td>{{ data[2] }}</td>
                    <td>{{ data[3] }}</td>
                    <td>{{ data[4] }}</td>
                    <td>{{ data[5] }}</td>
                    <td>{{ data[6] }}</td>
                    <td>{{ data[7] }}</td>
                    <td>{{ data[8] }}</td>
                    <td>{{ data[9] }}</td>
                    <td>{{ data[10] }}</td>
                    <td>{{ data[11] }}</td>
                    <td>{{ data[12] }}</td>
                    <td>
                        {% if data[13] == '正常' %}
                        <span><span class="status-indicator status-normal"></span>正常</span>
                        {% elif data[13] == '维护' %}
                        <span><span class="status-indicator status-warning"></span>维护</span>
                        {% elif data[13] == '不具备运行条件' %}
                        <span><span class="status-indicator status-danger"></span>不具备运行条件</span>
                        {% else %}
                        <span><span class="status-indicator status-danger"></span>未知</span>
                        {% endif %}
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>

    <!-- 图表模态框 -->
    <div id="chartModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>参数图表绘制</h3>
                <span class="close" onclick="closeChartModal()">&times;</span>
            </div>
            <div class="modal-body">
                <div class="parameter-selection">
                    <h4>请选择要绘制的参数：</h4>
                    <div class="parameter-grid">
                        <div class="parameter-item">
                            <input type="checkbox" id="water_temperature" name="parameters" value="4">
                            <label for="water_temperature">水温 (°C)</label>
                        </div>
                        <div class="parameter-item">
                            <input type="checkbox" id="ph" name="parameters" value="5">
                            <label for="ph">pH</label>
                        </div>
                        <div class="parameter-item">
                            <input type="checkbox" id="dissolved_oxygen" name="parameters" value="6">
                            <label for="dissolved_oxygen">溶解氧量 (mg/L)</label>
                        </div>
                        <div class="parameter-item">
                            <input type="checkbox" id="conductivity" name="parameters" value="7">
                            <label for="conductivity">电导率 (μS/cm)</label>
                        </div>
                        <div class="parameter-item">
                            <input type="checkbox" id="turbidity" name="parameters" value="8">
                            <label for="turbidity">浊度 (NTU)</label>
                        </div>
                        <div class="parameter-item">
                            <input type="checkbox" id="permanganate_index" name="parameters" value="9">
                            <label for="permanganate_index">高锰酸盐指数 (mg/L)</label>
                        </div>
                        <div class="parameter-item">
                            <input type="checkbox" id="ammonia_nitrogen" name="parameters" value="10">
                            <label for="ammonia_nitrogen">氨氮 (mg/L)</label>
                        </div>
                        <div class="parameter-item">
                            <input type="checkbox" id="total_phosphorus" name="parameters" value="11">
                            <label for="total_phosphorus">总磷 (mg/L)</label>
                        </div>
                        <div class="parameter-item">
                            <input type="checkbox" id="total_nitrogen" name="parameters" value="12">
                            <label for="total_nitrogen">总氮 (mg/L)</label>
                        </div>
                    </div>
                </div>

                <div class="control-buttons">
                    <button class="btn btn-primary" onclick="generateChart()">生成图表</button>
                    <button class="btn btn-secondary" onclick="clearChart()">清除图表</button>
                    <button class="btn btn-secondary" onclick="selectAll()">全选</button>
                    <button class="btn btn-secondary" onclick="clearAll()">清空选择</button>
                    <button class="btn btn-success" id="downloadBtn" onclick="downloadChart()" disabled>下载图表</button>
                </div>

                <div class="chart-container" id="chartContainer">
                    <canvas id="dataChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentChart = null;

        // 从Flask传入的数据
        const monitoringData = [
            {% for data in datas %}
            [
                "{{ data[0] }}", "{{ data[1] }}", "{{ data[2] }}", "{{ data[3] }}",
                "{{ data[4] }}", "{{ data[5] }}", "{{ data[6] }}", "{{ data[7] }}",
                "{{ data[8] }}", "{{ data[9] }}", "{{ data[10] }}", "{{ data[11] }}",
                "{{ data[12] }}", "{{ data[13] }}"
            ]{% if not loop.last %},{% endif %}
            {% endfor %}
        ];

        function openChartModal() {
            document.getElementById('chartModal').style.display = 'block';
        }

        function closeChartModal() {
            document.getElementById('chartModal').style.display = 'none';
        }

        function selectAll() {
            const checkboxes = document.querySelectorAll('input[name="parameters"]');
            checkboxes.forEach(checkbox => {
                checkbox.checked = true;
            });
        }

        function clearAll() {
            const checkboxes = document.querySelectorAll('input[name="parameters"]');
            checkboxes.forEach(checkbox => {
                checkbox.checked = false;
            });
        }

        function clearChart() {
            if (currentChart) {
                currentChart.destroy();
                currentChart = null;
            }
            document.getElementById('chartContainer').style.display = 'none';
            document.getElementById('downloadBtn').disabled = true;
        }

        function downloadChart() {
            if (!currentChart) {
                alert('请先生成图表！');
                return;
            }

            try {
                // 获取当前选中的参数名称
                const selectedParams = [];
                const checkboxes = document.querySelectorAll('input[name="parameters"]:checked');
                checkboxes.forEach(checkbox => {
                    selectedParams.push(checkbox.nextElementSibling.textContent);
                });

                // 生成文件名
                const currentDate = new Date();
                const dateStr = currentDate.getFullYear() + '-' +
                               String(currentDate.getMonth() + 1).padStart(2, '0') + '-' +
                               String(currentDate.getDate()).padStart(2, '0');
                const timeStr = String(currentDate.getHours()).padStart(2, '0') + '-' +
                               String(currentDate.getMinutes()).padStart(2, '0') + '-' +
                               String(currentDate.getSeconds()).padStart(2, '0');

                const fileName = `海洋监测数据图表_${dateStr}_${timeStr}.png`;

                // 创建下载链接
                const link = document.createElement('a');
                link.download = fileName;
                link.href = currentChart.toBase64Image('image/png', 1.0);

                // 触发下载
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);

                // 显示成功提示
                alert('图表下载成功！文件名：' + fileName);
            } catch (error) {
                console.error('下载失败:', error);
                alert('图表下载失败，请重试！');
            }
        }

        function generateChart() {
            const selectedParameters = [];
            const checkboxes = document.querySelectorAll('input[name="parameters"]:checked');

            if (checkboxes.length === 0) {
                alert('请至少选择一个参数！');
                return;
            }

            checkboxes.forEach(checkbox => {
                selectedParameters.push({
                    index: parseInt(checkbox.value),
                    label: checkbox.nextElementSibling.textContent
                });
            });

            // 清除之前的图表
            if (currentChart) {
                currentChart.destroy();
            }

            // 过滤和处理数据
            const filteredData = [];
            const seenDates = new Set();

            for (let row of monitoringData) {
                const dateStr = row[3];
                // 过滤掉'-'和重复的日期
                if (dateStr && dateStr !== '-' && !seenDates.has(dateStr)) {
                    const date = new Date(dateStr);
                    if (!isNaN(date.getTime())) {
                        seenDates.add(dateStr);
                        filteredData.push({
                            date: date,
                            dateStr: dateStr,
                            row: row
                        });
                    }
                }
            }

            // 按时间排序
            filteredData.sort((a, b) => a.date - b.date);

            if (filteredData.length === 0) {
                alert('没有有效的时间数据可用于绘制图表！');
                return;
            }

            // 生成4小时间隔的时间轴
            const startTime = filteredData[0].date;
            const endTime = filteredData[filteredData.length - 1].date;
            const timeLabels = [];
            const timeAxisData = {};

            // 创建4小时间隔的时间点
            let currentTime = new Date(startTime);
            // 将开始时间调整到最近的4小时整点
            currentTime.setMinutes(0, 0, 0);
            const hours = currentTime.getHours();
            currentTime.setHours(Math.floor(hours / 4) * 4);

            while (currentTime <= endTime) {
                const timeKey = currentTime.getTime();
                const timeLabel = currentTime.toLocaleDateString() + ' ' +
                                currentTime.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
                timeLabels.push(timeLabel);
                timeAxisData[timeKey] = null; // 初始化为空

                // 增加4小时
                currentTime = new Date(currentTime.getTime() + 4 * 60 * 60 * 1000);
            }

            // 将实际数据映射到最近的4小时时间点
            const datasets = selectedParameters.map((param, index) => {
                const colors = [
                    '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0',
                    '#9966FF', '#FF9F40', '#FF6384', '#C9CBCF', '#4BC0C0'
                ];

                const dataPoints = [];

                for (let i = 0; i < timeLabels.length; i++) {
                    const timeKey = Object.keys(timeAxisData)[i];
                    const targetTime = new Date(parseInt(timeKey));

                    // 找到最接近这个时间点的数据
                    let closestData = null;
                    let minTimeDiff = Infinity;

                    for (let data of filteredData) {
                        const timeDiff = Math.abs(data.date - targetTime);
                        if (timeDiff < minTimeDiff && timeDiff <= 2 * 60 * 60 * 1000) { // 2小时容差
                            minTimeDiff = timeDiff;
                            closestData = data;
                        }
                    }

                    if (closestData) {
                        const value = closestData.row[param.index];
                        if (value && value !== '-') {
                            const numValue = parseFloat(value);
                            dataPoints.push(isNaN(numValue) ? null : numValue);
                        } else {
                            dataPoints.push(null);
                        }
                    } else {
                        dataPoints.push(null);
                    }
                }

                return {
                    label: param.label,
                    data: dataPoints,
                    borderColor: colors[index % colors.length],
                    backgroundColor: colors[index % colors.length] + '20',
                    fill: false,
                    tension: 0.1,
                    spanGaps: true // 连接空值点
                };
            });

            // 显示图表容器
            document.getElementById('chartContainer').style.display = 'block';

            // 创建图表
            const ctx = document.getElementById('dataChart').getContext('2d');
            currentChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: timeLabels,
                    datasets: datasets
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: '监测时间'
                            },
                            ticks: {
                                maxRotation: 45,
                                minRotation: 0
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: '数值'
                            }
                        }
                    },
                    plugins: {
                        title: {
                            display: true,
                            text: '传感器监测数据变化趋势'
                        },
                        legend: {
                            display: true,
                            position: 'top'
                        },
                        tooltip: {
                            callbacks: {
                                title: function(context) {
                                    return '时间: ' + context[0].label;
                                },
                                label: function(context) {
                                    if (context.parsed.y === null) {
                                        return context.dataset.label + ': 无数据';
                                    }
                                    return context.dataset.label + ': ' + context.parsed.y;
                                }
                            }
                        }
                    },
                    interaction: {
                        intersect: false,
                        mode: 'index'
                    }
                }
            });
            document.getElementById('downloadBtn').disabled = false;
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('chartModal');
            if (event.target === modal) {
                closeChartModal();
            }
        }
    </script>
</body>
</html>